    //
//  Result.m
//  ShoppingCompare
//
//  Created by Wenjie on 11-5-12.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "LKGoogleTranslator.h"
#import "Register.h"
#import "Result.h"
#import "RootViewController.h"
#import "Search.h"
#import "Taobao.h"
#import "ItemList.h"
#import "CompareList.h"
#import "SubMenu.h"

static NSString* currentName = nil;

@implementation Result

- (NSInteger) numberOfSectionsInTableView:(UITableView*) tableView {
	return 1;
}

- (void)scrollViewDidScroll:(UIScrollView*) scrollView {
	int yPoint = scrollView.contentOffset.y;
	if (yPoint < -80 && pageNo > 1) {
		[self prevPage];
	}
	if (yPoint > 464 && pageNo < 100 && pageNo < (total + 9) / 10) {
		[self nextPage];
	}
}

- (void) nextPage {
	if (pageNo < 100 && pageNo < (total + 9) / 10) {
		RootViewController* rvc = (RootViewController*) [[UIApplication sharedApplication] delegate];
		UINavigationController* navi = [rvc->search navigationController];
		[navi popViewControllerAnimated:NO];
		[Taobao showSearchResult: ((pageNo < 100 && pageNo < (total + 9) / 10) ? (pageNo + 1) : pageNo)];
		Result* result = [[Result alloc]init];
		[navi pushViewController:result animated:YES];	
	}
}

- (void) prevPage {
	if (pageNo > 1) {
		RootViewController* rvc = (RootViewController*) [[UIApplication sharedApplication] delegate];
		UINavigationController* navi = [rvc->search navigationController];
		[navi popViewControllerAnimated:NO];
		[Taobao showSearchResult: pageNo - 1];
		Result* result = [[Result alloc]init];
		[navi pushViewController:result animated:YES];
	}
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [items count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	cell.backgroundColor = (indexPath.row % 2) ? [UIColor colorWithRed:0.88f green:0.93f blue:0.93f alpha:1.0f] : [UIColor colorWithRed:0.95f  green:0.97f blue:1.0f alpha:1.0f];
}

- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *) indexPath {
	item = [items objectAtIndex:indexPath.row];
	for (ItemList* oItem in listItems) {
		if ([item.imageURL isEqualToString:oItem.imageURL] && [item.nick isEqualToString:oItem.nick] && [item.title isEqualToString:oItem.title] && [item.price isEqualToString:oItem.price]) {
			item.selected = YES;
			break;
		}
	}
	UITableViewCellStyle style = UITableViewCellStyleSubtitle;
	UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:@"BaseCell"];
	
	if (!cell)
		cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"BaseCell"] autorelease];

	cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:item.imageURL]]];
	cell.textLabel.text = item.title;

	[cell.textLabel setFont:[UIFont fontWithName:@"Helvetica" size:15]];
	cell.textLabel.numberOfLines = 3;
	cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", item.nick, item.price];

	cell.accessoryType = (item.selected) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;	
	cell.textLabel.backgroundColor = cell.imageView.backgroundColor = cell.detailTextLabel.backgroundColor = [UIColor clearColor];
	return cell;
}

- (CGFloat) tableView:(UITableView*) tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 80.0f;
}

- (void)tableView:(UITableView*) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString* font = [[UIFont familyNames] objectAtIndex:indexPath.row];
	[((UILabel *) self.navigationItem.titleView) setText:font];
	[((UILabel *) self.navigationItem.titleView) setFont:[UIFont fontWithName:font size:18.0f]];
	
	item = [items objectAtIndex:indexPath.row];
	UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
	item.selected = !item.selected;
	cell.accessoryType = item.selected ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
}

- (id)init {
	if(self = [super init]) {
		item = [[[ItemList alloc] init] autorelease];

		total = 0;
		self.title = [NSString stringWithFormat:@"Result List %d", pageNo];
		self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Menu" style:UIBarButtonItemStylePlain target:self action:@selector(subMenu)] autorelease];
	}
   return self;
}
- (void) goRegister {
	RootViewController* rvc = (RootViewController*) [[UIApplication sharedApplication] delegate];
	UINavigationController* navi = [rvc->search navigationController];
	Register* regi = [[Register alloc]init];
	[navi pushViewController:regi animated:YES];
}

- (void) alertView: (UIAlertView *) alertView clickedButtonAtIndex:(NSInteger) buttonIndex {
	if (buttonIndex == 1) {
		RootViewController* rvc = (RootViewController*) [[UIApplication sharedApplication] delegate];
		UINavigationController* navi = [rvc->search navigationController];
		CompareList* compare = [[CompareList alloc]init];
		[navi pushViewController:compare animated:YES];

	}
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	//[item release];
    [super dealloc];
}

- (void)viewDidLoad {
	[items removeAllObjects];
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:resultData];
	[parser setShouldProcessNamespaces:NO];
	[parser setShouldReportNamespacePrefixes:NO];
	[parser setShouldResolveExternalEntities:NO];
	
	[parser setDelegate:self];
	[parser parse];
	[parser release];
	[super viewDidLoad];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	currentName = elementName;
	if (inTaobao) {
		if ([currentName isEqualToString:@"item"]) {
			item.title = @"";
		}
	} else {
		if ([currentName isEqualToString:@"Item"]) {
			item.title = @"";
		}
	}

}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	if (inTaobao) {
		if ([currentName isEqualToString:@"pic_url"]) {
			item.imageURL = string;
		}
		if ([currentName isEqualToString:@"price"]) {
			item.price = string;
		}
		if ([currentName isEqualToString:@"nick"]) {
			item.nick = string;
		}
		if ([currentName isEqualToString:@"title"]) {
			item.title = [item.title stringByAppendingString:string];
		}
		if ([currentName isEqualToString:@"total_results"]) {
			total = [string longLongValue];
		}
	} else {
		if ([currentName isEqualToString:@"ImageUrl"]) {
			item.imageURL = string;
		}
		if ([currentName isEqualToString:@"LowestPrice"]) {
			item.price = string;
		}
		if ([currentName isEqualToString:@"MakerName"]) {
			item.nick = string;
		}
		if ([currentName isEqualToString:@"ProductName"]) {
			item.title = [item.title stringByAppendingString:string];
		}
		if ([currentName isEqualToString:@"NumOfResult"]) {
			total = [string longLongValue];
		}
	}
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
	if (inTaobao) {
		if ([elementName isEqualToString:@"item"]) {
			item.title = [item.title stringByReplacingOccurrencesOfString: @"<span class=H>" withString: @""];
			item.title = [item.title stringByReplacingOccurrencesOfString: @"</span>" withString: @""];
			[items addObject: [[[ItemList alloc] initWithImageURL:item.imageURL andNick:item.nick andTitle:item.title andPrice:item.price] autorelease]];
													 
		}
	} else {
		if ([elementName isEqualToString:@"Item"]) {
			[items addObject: [[[ItemList alloc] initWithImageURL:item.imageURL andNick:item.nick andTitle:item.title andPrice:item.price] autorelease]];
		}
	}
}

- (void)subMenu {
	RootViewController* rvc = (RootViewController*) [[UIApplication sharedApplication] delegate];
	UINavigationController* navi = [rvc->search navigationController];
	SubMenu* subMenu = [[SubMenu alloc] init];
	[navi pushViewController:subMenu animated:YES];
}

@end